//
//  RegisterVC.swift
//  LeTu
//
//  Created by g1 on 2023/12/4.
//

import UIKit
import ActiveLabel

class RegisterVC: BaseViewController {

    private var viewModel = RegisterVM()
    
    private let bag = DisposeBag()
    private var isCountdown = false
    private var isAgree = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        eventHandle()
        
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        DispatchQueue.main.async {
            self.registerBtn.layerCornerRadius(CGFloat.app_btnHeight/2)
        }
    }
    func eventHandle() {
        
        // 限制手机号长度
        let countValid = phoneView.phoneTextField.rx.text.orEmpty.map { $0.count > 11 }.share(replay: 1)
        countValid.subscribe(onNext: { valid in
            if  valid {
                self.phoneView.phoneTextField.text = Utils.clipTextFieldTextLength(textField: self.phoneView.phoneTextField, limitNum: 11)
            }
            
        }).disposed(by: bag)
        
        // 限制验证码长度
        let authCodeValid = authCodeView.contentTextField.rx.text.orEmpty.map { $0.count > 6 }.share(replay: 1)
        authCodeValid.subscribe(onNext: { valid in
            if  valid {
                self.authCodeView.contentTextField.text = Utils.clipTextFieldTextLength(textField: self.authCodeView.contentTextField, limitNum: 6)
            }
            
        }).disposed(by: bag)
        
    }
    
    // MARK: - UIButtonAction
    @objc func agreementBtnAction() {
        isAgree = !isAgree
        agreementBtn.setImage(UIImage(named: isAgree ? "check_box_select":"check_box_unselect"))
    }
    @objc func getAuthCodeBtnAction() {
        
        guard let phoneNum = phoneView.phoneTextField.text, Utils.isMobile(mobile: phoneNum) else { return showMessage(message: "您的手机号码不正确".localized) }
        
        authCodeView.getAuthCodeBtn.isEnabled = false
        LoginVM.getVerificationCode(phoneNum: phoneNum) { [weak self] dialog in
            
            guard let strongSelf = self else { return }

            DispatchQueue.main.async {
                strongSelf.authCodeView.getAuthCodeBtn.isEnabled = true
                
                if dialog.code == 200 {
                    
                    Observable<Int>.timer(RxTimeInterval.seconds(0), period: RxTimeInterval.seconds(1), scheduler: MainScheduler.instance)
                        .map({60 - $0})
                        .take(60+1) //因为会接受0.。。。60共61个数字 60是无等待发送订阅即发送
                        .bind(onNext: { [weak self] (int) in
                            
                            DispatchQueue.main.async {
                                
                                guard let strongSelf = self else { return }
                                
                                if int > 0 {
                                    strongSelf.isCountdown = true
                                    strongSelf.authCodeView.getAuthCodeBtn.setTitle("\(int)s")
                                    strongSelf.authCodeView.getAuthCodeBtn.isEnabled = false
                                }else{
                                    strongSelf.authCodeView.getAuthCodeBtn.setTitle("重新获取")
                                    strongSelf.authCodeView.getAuthCodeBtn.isEnabled = true
                                    strongSelf.isCountdown = false
                                }
                            }
                        }).disposed(by: strongSelf.bag)
                    
                } else {
                    strongSelf.showMessage(message: dialog.message)
                }
                
            }
            
        }
        
    }
    @objc func registerBtnAction() {
        
        guard let phone = phoneView.phoneTextField.text, Utils.isMobile(mobile: phone) else { return showMessage(message: "请输入正确的手机号".localized) }
        guard let password = passwordView.contentTextField.text else { return showMessage(message: "请输入密码".localized) }
        guard password.count >= 6 else { return showMessage(message: "密码至少6位".localized) }
        guard let authCode = authCodeView.contentTextField.text, authCode.count > 0 else { return showMessage(message: "请输入验证码".localized) }
        guard let inviteCode = inviteCodeView.contentTextField.text, inviteCode.count > 0 else { return showMessage(message: "请输入邀请码".localized) }
        guard isAgree == true else { return showMessage(message: "请同意用户条款".localized) }
        
        let params = ["mobile": phone, "password": password, "verificationCode": authCode, "inviteCode": inviteCode]
        viewModel.register(params: params) {  [weak self] dialog in
            
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.hideIndicator()
                strongSelf.showMessage(message: dialog.message)
                if dialog.code == 200 {
                    strongSelf.backAction()
                }
            }
            
        }
        
    }
    
    // MARK: - configUI
    func configUI() {
        
        view.addSubview(naviBar)
        view.addSubview(logoImgView)
        view.addSubview(accountBackView)
        accountBackView.addSubview(accountLabel)
        accountBackView.addSubview(phoneView)
        view.addSubview(passwordBackView)
        passwordBackView.addSubview(passwordLabel)
        passwordBackView.addSubview(passwordView)
        view.addSubview(authCodeBackView)
        authCodeBackView.addSubview(authCodeLabel)
        authCodeBackView.addSubview(authCodeView)
        view.addSubview(inviteCodeBackView)
        inviteCodeBackView.addSubview(inviteCodeLabel)
        inviteCodeBackView.addSubview(inviteCodeView)
        view.addSubview(registerBtn)
        view.addSubview(protocalBackView)
        protocalBackView.addSubview(agreementBtn)
        protocalBackView.addSubview(agreementLabel)
        
        naviBar.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(Size.navigationBarHeight)
        }
        logoImgView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(naviBar.snp.bottom).offset(20)
            make.height.width.equalTo(66)
        }
        accountBackView.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.right.equalTo(-22)
            make.top.equalTo(logoImgView.snp.bottom).offset(50)
        }
        accountLabel.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.top.equalToSuperview()
        }
        phoneView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(50)
            make.top.equalTo(accountLabel.snp.bottom).offset(6)
        }
        passwordBackView.snp.makeConstraints { make in
            make.left.right.equalTo(accountBackView)
            make.top.equalTo(accountBackView.snp.bottom).offset(24)
        }
        passwordLabel.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.top.equalToSuperview()
        }
        passwordView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(50)
            make.top.equalTo(passwordLabel.snp.bottom).offset(6)
        }
        authCodeBackView.snp.makeConstraints { make in
            make.left.right.equalTo(accountBackView)
            make.top.equalTo(passwordBackView.snp.bottom).offset(24)
        }
        authCodeLabel.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.top.equalToSuperview()
        }
        authCodeView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(50)
            make.top.equalTo(authCodeLabel.snp.bottom).offset(6)
        }
        inviteCodeBackView.snp.makeConstraints { make in
            make.left.right.equalTo(accountBackView)
            make.top.equalTo(authCodeBackView.snp.bottom).offset(24)
        }
        inviteCodeLabel.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.top.equalToSuperview()
        }
        inviteCodeView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(50)
            make.top.equalTo(inviteCodeLabel.snp.bottom).offset(6)
        }
        registerBtn.snp.makeConstraints { make in
            make.left.right.equalTo(accountBackView)
            make.top.equalTo(inviteCodeBackView.snp.bottom).offset(45)
            make.height.equalTo(CGFloat.app_btnHeight)
        }
        protocalBackView.snp.makeConstraints { make in
            make.left.equalTo(registerBtn)
            make.right.equalTo(registerBtn).offset(-16)
            make.height.lessThanOrEqualTo(36)
            make.top.equalTo(registerBtn.snp.bottom).offset(12)
        }
        agreementBtn.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.height.equalTo(33)
        }
        agreementLabel.snp.makeConstraints { make in
            make.left.equalTo(agreementBtn.snp.right)
            make.top.bottom.right.equalToSuperview()
        }
        
        configAgreementPromptLabel()
        
        agreementBtn.addTarget(self, action: #selector(agreementBtnAction))
        registerBtn.addTarget(self, action: #selector(registerBtnAction))
        
    }
    func configAgreementPromptLabel() {
        
        let customType1Name = "《用户协议》".localized
        let customType2Name = "《隐私政策》".localized

        let customType1 = ActiveType.custom(pattern: customType1Name)
        let customType2 = ActiveType.custom(pattern: customType2Name)

        agreementLabel.enabledTypes = [customType1,customType2]
        agreementLabel.font = kSetPingFangRegular(12)
        agreementLabel.customColor[customType1] = .app_themeColor
        agreementLabel.customColor[customType2] = agreementLabel.customColor[customType1]

        agreementLabel.text = "我已阅读并同意\(customType1Name)和\(customType2Name)，未注册的手机号将自动创建本应用账号".localized
        agreementLabel.handleCustomTap(for: customType1, handler: { (customType) in
            self.present(BaseNavigationController(rootViewController: AppWebViewController(url: kUserProtocalUrl, isShowNav: true)), animated: true, completion: nil)
        })
        agreementLabel.handleCustomTap(for: customType2, handler: { (customType) in
            self.present(BaseNavigationController(rootViewController: AppWebViewController(url: kPrivateProtocalUrl, isShowNav: true)), animated: true, completion: nil)
        })
        
        passwordView.contentTextField.delegate = self
        inviteCodeView.contentTextField.delegate = self
        
    }
    private lazy var naviBar = BasePresentNavBar(title: "注册".localized, target: self, action: #selector(backAction))
    private lazy var logoImgView: UIImageView = {
        let logoImgView = UIImageView()
        logoImgView.image = UIImage(named: "logo_icon")
        logoImgView.contentMode = .scaleAspectFit
        return logoImgView
    }()
    // - 账号
    private lazy var accountBackView = UIView()
    private lazy var accountLabel: UILabel = {
        let accountLabel = UILabel()
        accountLabel.text = "手机号码".localized
        accountLabel.font = kSetPingFangMedium(15)
        accountLabel.textColor = .app_textDarkGrayColor
        return accountLabel
    }()
    private lazy var phoneView: LoginPhoneView = {
        let phoneView = LoginPhoneView()
        phoneView.placeholder = "请输入手机号码".localized
        return phoneView
    }()
    // - 密码
    private lazy var passwordBackView: UIView = {
        let passwordBackView = UIView()
        return passwordBackView
    }()
    private lazy var passwordLabel: UILabel = {
        let passwordLabel = UILabel()
        passwordLabel.text = "密码".localized
        passwordLabel.font = kSetPingFangMedium(15)
        passwordLabel.textColor = .app_textDarkGrayColor
        return passwordLabel
    }()
    private lazy var passwordView = LoginInputView(placeholder: "请输入密码".localized)
    // - 验证码
    private lazy var authCodeBackView: UIView = {
        let authCodeBackView = UIView()
        return authCodeBackView
    }()
    private lazy var authCodeLabel: UILabel = {
        let passwordLabel = UILabel()
        passwordLabel.text = "验证码".localized
        passwordLabel.font = kSetPingFangMedium(15)
        passwordLabel.textColor = .app_textDarkGrayColor
        return passwordLabel
    }()
    private lazy var authCodeView = LoginAuthCodeView(placeholder: "请输入验证码".localized, target: self, action: #selector(getAuthCodeBtnAction))
    // - 邀请码
    private lazy var inviteCodeBackView: UIView = {
        let inviteCodeBackView = UIView()
        return inviteCodeBackView
    }()
    private lazy var inviteCodeLabel: UILabel = {
        let inviteCodeLabel = UILabel()
        inviteCodeLabel.text = "邀请码".localized
        inviteCodeLabel.font = kSetPingFangMedium(15)
        inviteCodeLabel.textColor = .app_textDarkGrayColor
        return inviteCodeLabel
    }()
    private lazy var inviteCodeView = LoginInputView(placeholder: "请输入邀请码".localized)
    // - 注册
    private lazy var registerBtn: GradientButton = {
        let registerBtn = GradientButton()
        registerBtn.setTitle("新用户注册".localized)
        registerBtn.gradientColors = UIColor.app_themeGradientColors
        return registerBtn
    }()
    // - 用户协议
    private lazy var protocalBackView = UIView()
    private lazy var agreementBtn: CustomClickableView = {
        let agreementBtn = CustomClickableView()
        agreementBtn.setImage(UIImage(named: "check_box_unselect"))
        agreementBtn.setImageEdgeInsets(UIEdgeInsets(top: 3, left: 14, bottom: 17, right: 4))
        return agreementBtn
    }()
    private lazy var agreementLabel: ActiveLabel = {
        let agreementLabel = ActiveLabel()
        agreementLabel.font = kSetPingFangRegular(11)
        agreementLabel.textColor = UIColor(red: 0.494, green: 0.51, blue: 0.514, alpha: 1)
        agreementLabel.numberOfLines = 0
        return agreementLabel
    }()

}

extension RegisterVC: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
}
